package cn.tedu.mall.admin.security;

import cn.tedu.mall.admin.mapper.AdminMapper;
import cn.tedu.mall.admin.pojo.vo.AdminLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Security自动调用的UserDetailsService实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    public UserDetailsServiceImpl() {
        log.debug("创建Security框架自动调用的UserDetailsService实现类对象：UserDetailsServiceImpl");
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动根据用户名【{}】查询用户详情", s);

        // 执行查询
        AdminLoginVO admin = adminMapper.getByUsername(s);
        // 判断是否查询到有效结果
        if (admin != null) {
            log.debug("查询到匹配的管理员信息：{}", admin);

            // 将查询结果中的权限信息转换成Security要求的格式
            List<String> permissions = admin.getPermissions();
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }

            // 返回自定义的UserDetails类型的对象
            AdminDetails adminDetails = new AdminDetails(
                    admin.getUsername(),
                    admin.getPassword(),
                    admin.getEnable() == 1,
                    authorities
            );
            adminDetails.setId(admin.getId());
            log.debug("即将向Spring Security返回AdminDetails：{}", adminDetails);
            return adminDetails;
        }

        log.error("没有查询到匹配的管理员信息");
        return null;
    }

}
